package com.sfeir.poc.portal.gui.client.controller;

import java.util.ArrayList;
import java.util.List;

import com.sfeir.poc.portal.gui.client.events.ApplicationEvent;
import com.sfeir.poc.portal.gui.client.events.ApplicationEventListener;
import com.sfeir.poc.portal.gui.client.events.ApplicationEventProvider;
import com.sfeir.poc.portal.gui.client.events.ApplicationEventType;

/**
 * 
 * Controller that dispatch events
 *
 */
public class Controller implements ApplicationEventProvider, ApplicationEventListener {

	private final List<ApplicationEventListener> applicationListeners = new ArrayList<ApplicationEventListener>();

	public Controller() {
	}

	public void onActionFired(ApplicationEvent event) {
		if (event == null) {
			return;
		}

		switch (event.getType()) {
		case RETRIEVE_WIDGETS:
			fireActionEvent(ApplicationEventType.GET_WIDGETS, event.getContext());
			break;
		case WIDGETS_UPDATED:
			fireActionEvent(ApplicationEventType.CREATE_WIDGETS, event.getContext());
			break;
		case WIDGET_UPDATED:
			fireActionEvent(ApplicationEventType.CREATE_WIDGET_VIEW, event.getContext());
			break;
		case RETRIEVE_FEED:
			fireActionEvent(ApplicationEventType.GET_FEED, event.getContext());
			break;
		case UPDATE_FEED:
			fireActionEvent(ApplicationEventType.UPDATE_FACTORY, event.getContext());
			break;
		case UPDATE_WIDGETS:
			fireActionEvent(ApplicationEventType.CREATE_WIDGET_VIEWS, event.getContext());
			break;
		case RENDER_WIDGETS:
			fireActionEvent(ApplicationEventType.DISPLAY_WIDGETS, event.getContext());
			break;
		case RENDER_WIDGET:
			fireActionEvent(ApplicationEventType.DISPLAY_WIDGET, event.getContext());
			break;
		case GET_TAB_TITLE:
			fireActionEvent(ApplicationEventType.GET_SHEET_TITLE, event.getContext());
			break;
		case UPDATE_SHEET_TITLE:
			fireActionEvent(ApplicationEventType.UPDATE_TAB, event.getContext());
			break;
		default:	
			break;
		}

	}

	public void addApplicationEventListener(final ApplicationEventListener listener) {
		if (!this.applicationListeners.contains(listener)) {
			this.applicationListeners.add(listener);
		}
	}

	public void removeApplicationEventListener(final ApplicationEventListener listener) {
		if (this.applicationListeners.contains(listener)) {
			this.applicationListeners.remove(listener);
		}
	}

	public void fireActionEvent(final ApplicationEventType type, final Object eventContext) {
		final ApplicationEvent event = new ApplicationEvent(type, eventContext);

		for (ApplicationEventListener listener : this.applicationListeners) {
			listener.onActionFired(event);
		}
	}

}
